package com.ympc.controller;

import com.ympc.pojo.PPT;
import com.ympc.pojo.Teacher;
import com.ympc.pojo.Users;
import com.ympc.service.PPTService;
import com.ympc.service.TeacherService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * PPT管理控制器（授课）
 */
@Controller
@RequestMapping("/ppt")
public class PPTController {
    
    @Resource
    private PPTService pptService;
    
    @Resource
    private TeacherService teacherService;
    
    /**
     * PPT列表页面
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String pptList(HttpSession session, Model model) {
        try {
            Users user = (Users) session.getAttribute("user");
            if (user == null) {
                return "redirect:/";
            }
            
            // 先尝试从session获取teacher，避免重复查询
            Teacher teacher = (Teacher) session.getAttribute("teacher");
            if (teacher == null || teacher.getId() == null) {
                try {
                    teacher = teacherService.getTeacherByUserId(user.getId());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                
                if (teacher == null || teacher.getId() == null) {
                    // 创建一个空的teacher对象，避免模板中访问null
                    teacher = new Teacher();
                    teacher.setUserId(user.getId());
                    session.setAttribute("teacher", teacher);
                    return "redirect:/teacher/profile";
                }
                session.setAttribute("teacher", teacher);
            }
            
            List<PPT> ppts = new java.util.ArrayList<>();
            try {
                ppts = pptService.getPPTsByTeacherId(teacher.getId());
                if (ppts == null) {
                    ppts = new java.util.ArrayList<>();
                }
            } catch (Exception e) {
                e.printStackTrace();
                // 如果表不存在，返回空列表，但不阻止页面渲染
                ppts = new java.util.ArrayList<>();
                String errorMsg = e.getMessage();
                if (errorMsg != null && (errorMsg.contains("Table") || errorMsg.contains("doesn't exist") || errorMsg.contains("不存在"))) {
                    model.addAttribute("error", "PPT表不存在，请先执行create_ppt_table.sql脚本创建表。");
                } else {
                    model.addAttribute("error", "查询PPT列表时出错：" + (errorMsg != null ? errorMsg : "未知错误"));
                }
            }
            
            model.addAttribute("ppts", ppts);
            model.addAttribute("teacher", teacher);
            return "ppt/list";
        } catch (Exception e) {
            e.printStackTrace();
            // 确保返回一个有效的视图，即使发生异常
            model.addAttribute("ppts", new java.util.ArrayList<>());
            model.addAttribute("error", "加载页面时出错：" + (e.getMessage() != null ? e.getMessage() : "未知错误"));
            // 确保teacher对象存在
            Teacher teacher = (Teacher) session.getAttribute("teacher");
            if (teacher == null) {
                teacher = new Teacher();
                session.setAttribute("teacher", teacher);
            }
            model.addAttribute("teacher", teacher);
            return "ppt/list";
        }
    }
    
    /**
     * 上传PPT
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String uploadPPT(@RequestParam("file") MultipartFile file,
                            @RequestParam(required = false) String pptName,
                            @RequestParam(required = false) String description,
                            HttpSession session,
                            RedirectAttributes redirectAttributes) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Teacher teacher = teacherService.getTeacherByUserId(user.getId());
        if (teacher == null || teacher.getId() == null) {
            redirectAttributes.addFlashAttribute("error", "请先完善教师信息");
            return "redirect:/teacher/profile";
        }
        
        if (file == null || file.isEmpty()) {
            redirectAttributes.addFlashAttribute("error", "请选择要上传的PPT文件");
            return "redirect:/ppt/list";
        }
        
        // 验证文件类型
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || (!originalFilename.toLowerCase().endsWith(".ppt") && !originalFilename.toLowerCase().endsWith(".pptx"))) {
            redirectAttributes.addFlashAttribute("error", "只能上传PPT文件（.ppt或.pptx格式）");
            return "redirect:/ppt/list";
        }
        
        try {
            // 创建上传目录
            String uploadDir = "uploads/ppt/";
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            
            // 生成文件名：teacher_教师ID_时间戳.扩展名
            String extension = "";
            if (originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String fileName = "teacher_" + teacher.getId() + "_" + System.currentTimeMillis() + extension;
            String filePath = uploadDir + fileName;
            Path destPath = uploadPath.resolve(fileName);
            
            // 保存文件
            Files.copy(file.getInputStream(), destPath);
            
            // 创建PPT记录
            PPT ppt = new PPT();
            ppt.setTeacherId(teacher.getId());
            ppt.setPptName(pptName != null && !pptName.isEmpty() ? pptName : originalFilename);
            ppt.setFilePath(filePath);
            ppt.setFileName(originalFilename);
            ppt.setFileSize(file.getSize());
            ppt.setDescription(description);
            
            boolean success = pptService.createPPT(ppt);
            if (success) {
                redirectAttributes.addFlashAttribute("message", "PPT上传成功");
            } else {
                redirectAttributes.addFlashAttribute("error", "PPT上传失败");
                // 删除已上传的文件
                try {
                    Files.delete(destPath);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            String errorMsg = e.getMessage();
            if (errorMsg != null && (errorMsg.contains("Table") || errorMsg.contains("doesn't exist") || errorMsg.contains("不存在"))) {
                redirectAttributes.addFlashAttribute("error", "PPT表不存在，请先执行create_ppt_table.sql脚本创建表。");
            } else {
                redirectAttributes.addFlashAttribute("error", "上传PPT时出错：" + errorMsg);
            }
        }
        
        return "redirect:/ppt/list";
    }
    
    /**
     * 删除PPT
     */
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String deletePPT(@RequestParam Integer pptId,
                            HttpSession session,
                            RedirectAttributes redirectAttributes) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Teacher teacher = teacherService.getTeacherByUserId(user.getId());
        if (teacher == null || teacher.getId() == null) {
            redirectAttributes.addFlashAttribute("error", "请先完善教师信息");
            return "redirect:/teacher/profile";
        }
        
        PPT ppt = pptService.getPPTById(pptId);
        if (ppt == null) {
            redirectAttributes.addFlashAttribute("error", "PPT不存在");
            return "redirect:/ppt/list";
        }
        
        // 验证权限：只有PPT所属教师可以删除
        if (!ppt.getTeacherId().equals(teacher.getId())) {
            redirectAttributes.addFlashAttribute("error", "无权删除此PPT");
            return "redirect:/ppt/list";
        }
        
        try {
            // 删除文件
            if (ppt.getFilePath() != null && !ppt.getFilePath().isEmpty()) {
                try {
                    Path filePath = Paths.get(ppt.getFilePath());
                    if (Files.exists(filePath)) {
                        Files.delete(filePath);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    // 继续删除数据库记录
                }
            }
            
            // 删除数据库记录
            boolean success = pptService.deletePPT(pptId);
            if (success) {
                redirectAttributes.addFlashAttribute("message", "PPT删除成功");
            } else {
                redirectAttributes.addFlashAttribute("error", "PPT删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("error", "删除PPT时出错：" + e.getMessage());
        }
        
        return "redirect:/ppt/list";
    }
    
    /**
     * 下载PPT
     */
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public ResponseEntity<org.springframework.core.io.Resource> downloadPPT(@RequestParam Integer pptId,
                                                                             HttpSession session) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return ResponseEntity.notFound().build();
        }
        
        Teacher teacher = teacherService.getTeacherByUserId(user.getId());
        if (teacher == null || teacher.getId() == null) {
            return ResponseEntity.notFound().build();
        }
        
        PPT ppt = pptService.getPPTById(pptId);
        if (ppt == null) {
            return ResponseEntity.notFound().build();
        }
        
        // 验证权限
        if (!ppt.getTeacherId().equals(teacher.getId())) {
            return ResponseEntity.notFound().build();
        }
        
        try {
            File file = new File(ppt.getFilePath());
            if (!file.exists()) {
                return ResponseEntity.notFound().build();
            }
            
            FileSystemResource resource = new FileSystemResource(file);
            
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + ppt.getFileName() + "\"")
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .contentLength(file.length())
                    .body(resource);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 在线预览PPT
     */
    @RequestMapping(value = "/view", method = RequestMethod.GET)
    public String viewPPT(@RequestParam Integer pptId,
                          HttpSession session,
                          Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Teacher teacher = teacherService.getTeacherByUserId(user.getId());
        if (teacher == null || teacher.getId() == null) {
            model.addAttribute("error", "请先完善教师信息");
            return "redirect:/teacher/profile";
        }
        
        PPT ppt = pptService.getPPTById(pptId);
        if (ppt == null) {
            model.addAttribute("error", "PPT不存在");
            return "redirect:/ppt/list";
        }
        
        // 验证权限
        if (!ppt.getTeacherId().equals(teacher.getId())) {
            model.addAttribute("error", "无权访问此PPT");
            return "redirect:/ppt/list";
        }
        
        String fileUrl = "/ppt_files/" + ppt.getFilePath().replace("uploads/ppt/", "");
        model.addAttribute("fileUrl", fileUrl);
        model.addAttribute("pptName", ppt.getPptName());
        model.addAttribute("pptId", pptId);
        
        return "ppt/view";
    }
}

